/*
  将下面异步代码使用 Promise 的方法改进
  尽量用看上去像同步代码的方式
  setTimeout(function () {
    var a = 'hello'
    setTimeout(function () {
      var b = 'lagou'
      setTimeout(function () {
        var c = 'I ♥ U'
        console.log(a + b +c)
      }, 10)
    }, 10)
  }, 10)
*/

// setTimeout(function () {
//   var a = 'hello'
//   setTimeout(function () {
//     var b = 'lagou'
//     setTimeout(function () {
//       var c = 'I ♥ U'
//       console.log(a + b +c)
//     }, 10)
//   }, 10)
// }, 10)

const sleep = time => new Promise(resolve => setTimeout(resolve, time));

const print = {
  _cache: [],
  set(txt, options = {}) {
    const { delay = 0 } = options;
    this._cache.push({ txt, delay });
    return this;
  },
  async log() {
    const finalLog = [];
    for (let i = 0, len = this._cache.length; i < len; i += 1) {
      const { txt, delay } = this._cache[i];
      await sleep(delay);
      finalLog.push(txt);
    }
    console.log(finalLog.join(''));
    this._cache.length = 0;
  },
  sleep(time) {
    if (time) return new Promise(resolve => setTimeout(resolve, time));
  }
}

print
  .set('hello', { delay: 1000 })
  .set('lagou', { delay: 1000 })
  .set('I ♥ U', { delay: 1000 })
  .log();
